package com.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * 77. 组合
 * 递归实现组合型枚举
 *
 * @author fy
 * @date 2022/4/28 19:48
 */
public class Solution77 {

    private List<List<Integer>> res;
    private int n;
    private int k;

    public List<List<Integer>> combine(int n, int k) {
        this.res = new ArrayList<>();
        if (n <= 0 || k <= 0 || k > n) {
            return res;
        }
        this.n = n;
        this.k = k;
        combine(1, new ArrayList<>());
        return res;
    }

    private void combine(int index, List<Integer> preList) {
        if (preList.size() + (n - index + 1) < k) {
            return;
        }
        // 记录合法的答案
        if (k == preList.size()) {
            res.add(new ArrayList<>(preList));
            return;
        }
        // 剪枝：preList 长度加上区间 [index, n] 的长度小于 k，不可能构造出长度为 k 的 preList
        for (int i = index; i <= n - (k - preList.size()) + 1; i++) {
            preList.add(i);
            combine(i + 1, preList);
            preList.remove(preList.size() - 1);
        }
    }

    public static void main(String[] args) {
        int n = 4;
        int k = 2;
        List<List<Integer>> res = new Solution77().combine(n, k);
        System.out.println(res);
    }

}
